#include "TextProcessor.h"
#include "PlatformTypeManager.h"
#include <iostream>
#include <string>
#include <filesystem>

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <limits.h>
#endif

namespace fs = std::filesystem;

int main(int argc, char* argv[]) {
    std::string jsonFilePath;
    std::string dbPath = "platform.db"; // 默认数据库路径
    
    // 检查命令行参数
    if (argc > 1) {
        jsonFilePath = argv[1];
        
        if (argc > 2) {
            // 如果提供了第二个参数，将其作为数据库路径
            dbPath = argv[2];
        }
    } else {
        // 如果没有提供参数，使用默认路径（当前工程目录下的test.json）
        jsonFilePath = "test.json";
    }
    
    // 初始化平台类型管理器
    PlatformTypeManager& manager = PlatformTypeManager::getInstance();
    
    // 尝试不同位置的数据库路径
    if (!manager.initialize(dbPath)) {
        std::cout << "Failed to initialize with path: " << dbPath << ". Trying alternative paths..." << std::endl;
        
        // 尝试相对于可执行文件的路径
        std::string exePath;
        
#ifdef _WIN32
        char buffer[MAX_PATH];
        GetModuleFileNameA(NULL, buffer, MAX_PATH);
        exePath = std::string(buffer);
        
        // 获取可执行文件所在的目录
        size_t pos = exePath.find_last_of("\\/");
        std::string exeDir = (pos != std::string::npos) ? exePath.substr(0, pos) : "";
        
        dbPath = exeDir + "\\..\\..\\debug\\platform.db";
#else
        char buffer[PATH_MAX];
        ssize_t len = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1);
        if (len != -1) {
            buffer[len] = '\0';
            exePath = std::string(buffer);
            
            // 获取可执行文件所在的目录
            size_t pos = exePath.find_last_of("/");
            std::string exeDir = (pos != std::string::npos) ? exePath.substr(0, pos) : "";
            
            dbPath = exeDir + "/../../debug/platform.db";
        }
#endif

        // 再次尝试初始化
        if (!manager.initialize(dbPath)) {
            std::cerr << "Failed to initialize PlatformTypeManager with database: " << dbPath << std::endl;
            std::cerr << "Will continue without platform type definitions." << std::endl;
        }
    }
    
    // 创建处理器实例
    TextProcessor processor;
    
    // 读取JSON文件
    if (!processor.readJsonFile(jsonFilePath)) {
        std::cerr << "Failed to read JSON file, program terminated." << std::endl;
        return 1;
    }
    
    // 处理JSON内容
    if (!processor.processJsonContent()) {
        std::cerr << "Failed to process JSON content, program terminated." << std::endl;
        return 1;
    }
    
    std::cout << "JSON processing completed successfully!" << std::endl;
    
    return 0;
} 